'use strict'

const Controller = require('egg').Controller

class HomeController extends Controller {
  //车次管理数据
  async trainList() {
    const { ctx } = this
    const list = await this.app.mysql.select('train')
    ctx.body = {
      code: 200,
      msg: '车次数据请求成功',
      list,
    }
  }

  //编辑
  async trainEdit() {
    const { ctx } = this
    const { id, trains, conductor, carriageAll, seatAll, maxnum, time, type } =
      ctx.request.body
    const row = {
      id,
      trains,
      conductor,
      carriageAll,
      seatAll,
      maxnum,
      time,
      type,
    }
    const res = await this.app.mysql.update('train', row)
    if (res.affectedRows === 1) {
      const list = await this.app.mysql.select('train')
      ctx.body = {
        code: 200,
        msg: '修改成功',
        list,
      }
    } else {
      ctx.body = {
        code: 404,
        msg: '修改失败',
      }
    }
  }

  //添加
  async trainAdd() {
    const { ctx } = this
    const { trains, conductor, type } = ctx.request.body
    const res = await this.app.mysql.insert('train', {
      trains: `${trains}`,
      conductor: `${conductor}`,
      carriageAll: 8,
      seatAll: 586,
      maxnum: '646',
      time: new Date().toLocaleString(),
      type: `${type}`,
      city: '1',
    })
    if (res.affectedRows === 1) {
      const list = await this.app.mysql.select('train')
      ctx.body = {
        code: 200,
        msg: '添加成功',
        list,
      }
    } else {
      ctx.body = {
        code: 404,
        msg: '添加失败',
      }
    }
  }
  //删除
  async trainDel() {
    const { ctx } = this
    const { id } = ctx.query
    const res = await this.app.mysql.delete('train', {
      id,
    })
    if (res.affectedRows === 1) {
      const list = await this.app.mysql.select('train')
      ctx.body = {
        code: 200,
        msg: '删除成功',
        list,
      }
    } else {
      ctx.body = {
        code: 404,
        msg: '删除失败',
      }
    }
  }
}

module.exports = HomeController
